<script setup>
import { ref, computed } from 'vue';
import CodeBlock from '@components/CodeBlock.vue'

// ===== 1. 可复用的组合式函数定义 =====

// 1.1 计数器组合式函数
function useCounter(initialValue = 0, step = 1) {
  const count = ref(initialValue);
  
  const increment = () => {
    count.value += step;
  };
  
  const decrement = () => {
    count.value -= step;
  };
  
  const reset = () => {
    count.value = initialValue;
  };
  
  return {
    count,
    increment,
    decrement,
    reset
  };
}

// 1.2 计时器组合式函数
function useTimer() {
  const seconds = ref(0);
  let timer = null;
  
  const start = () => {
    if (!timer) {
      timer = setInterval(() => {
        seconds.value++;
      }, 1000);
    }
  };
  
  const stop = () => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };
  
  const reset = () => {
    seconds.value = 0;
    stop();
  };
  
  // 在组件卸载时自动清理
  // 注意：在实际使用中，应该在组件的 onUnmounted 钩子中调用 stop()
  
  return {
    seconds,
    start,
    stop,
    reset
  };
}

// 1.3 本地存储组合式函数
function useLocalStorage(key, initialValue = '') {
  // 尝试从localStorage获取值
  const storedValue = localStorage.getItem(key);
  const value = ref(storedValue !== null ? storedValue : initialValue);
  
  const save = (newValue) => {
    value.value = newValue;
    localStorage.setItem(key, newValue);
  };
  
  const remove = () => {
    value.value = initialValue;
    localStorage.removeItem(key);
  };
  
  return {
    value,
    save,
    remove
  };
}

// 1.4 表单验证组合式函数
function useFormValidator(initialData, validationRules) {
  const data = ref({ ...initialData });
  const errors = ref({});
  
  const validateField = (field, value) => {
    if (validationRules[field]) {
      return validationRules[field](value);
    }
    return '';
  };
  
  const validateAll = () => {
    const newErrors = {};
    let isValid = true;
    
    Object.keys(data.value).forEach(field => {
      const error = validateField(field, data.value[field]);
      if (error) {
        newErrors[field] = error;
        isValid = false;
      }
    });
    
    errors.value = newErrors;
    return isValid;
  };
  
  const updateField = (field, value) => {
    data.value[field] = value;
    const error = validateField(field, value);
    
    if (error) {
      errors.value[field] = error;
    } else if (errors.value[field]) {
      delete errors.value[field];
    }
  };
  
  const reset = () => {
    data.value = { ...initialData };
    errors.value = {};
  };
  
  return {
    data,
    errors,
    validateField,
    validateAll,
    updateField,
    reset
  };
}

// 1.5 鼠标位置组合式函数
function useMouse() {
  const x = ref(0);
  const y = ref(0);
  
  const updateMousePosition = (event) => {
    x.value = event.clientX;
    y.value = event.clientY;
  };
  
  const startTracking = () => {
    window.addEventListener('mousemove', updateMousePosition);
  };
  
  const stopTracking = () => {
    window.removeEventListener('mousemove', updateMousePosition);
  };
  
  // 在组件卸载时自动清理
  
  return {
    x,
    y,
    startTracking,
    stopTracking
  };
}

// 1.6 网络请求组合式函数
function useFetch(url) {
  const data = ref(null);
  const loading = ref(false);
  const error = ref(null);
  
  const fetchData = async () => {
    loading.value = true;
    error.value = null;
    
    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      data.value = await response.json();
    } catch (err) {
      error.value = err.message;
    } finally {
      loading.value = false;
    }
  };
  
  return {
    data,
    loading,
    error,
    fetchData
  };
}

// ===== 2. 在组件中使用组合式函数 =====

// 2.1 使用计数器组合式函数
const { 
  count: counterCount, 
  increment: counterIncrement, 
  decrement: counterDecrement, 
  reset: counterReset 
} = useCounter(0, 1);

// 2.2 使用计时器组合式函数
const { 
  seconds: timerSeconds, 
  start: timerStart, 
  stop: timerStop, 
  reset: timerReset 
} = useTimer();

// 2.3 使用本地存储组合式函数
const { 
  value: savedText, 
  save: saveText, 
  remove: removeText 
} = useLocalStorage('demo-text', '这是存储在localStorage中的文本');

// 2.4 使用表单验证组合式函数
const formValidator = useFormValidator(
  { username: '', email: '' },
  {
    username: value => !value ? '用户名不能为空' : '',
    email: value => {
      if (!value) return '邮箱不能为空';
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return !emailRegex.test(value) ? '请输入有效的邮箱地址' : '';
    }
  }
);

// 2.5 使用鼠标位置组合式函数
const { 
  x: mouseX, 
  y: mouseY, 
  startTracking: startMouseTracking, 
  stopTracking: stopMouseTracking 
} = useMouse();

// 2.6 使用网络请求组合式函数 (模拟API)
const { 
  data: apiData, 
  loading: apiLoading, 
  error: apiError, 
  fetchData: fetchApiData 
} = useFetch('https://jsonplaceholder.typicode.com/todos/1');

// 启动鼠标跟踪
startMouseTracking();

// 清理函数
const cleanup = () => {
  stopMouseTracking();
  timerStop();
};

// 在实际组件中，应该在组件卸载时调用清理函数
// onUnmounted(cleanup);
</script>

<template>
  <div class="composables-demo">
    <h2 class="demo-title">🧩 Vue 3 组合式函数库演示</h2>
    
    <p class="demo-description">
      组合式函数是Vue 3中复用逻辑的强大方式，遵循"组合优于继承"的原则，可以灵活地组合各种功能逻辑。
    </p>
    
    <div class="demo-grid">
      <!-- 计数器组合式函数 -->
      <div class="demo-card">
        <h3 class="card-title">useCounter - 计数器</h3>
        <div class="demo-content">
          <div class="counter-display">
            计数: <span class="count-value">{{ counterCount }}</span>
          </div>
          <div class="button-group">
            <button class="action-btn" @click="counterDecrement">-</button>
            <button class="action-btn" @click="counterIncrement">+</button>
            <button class="action-btn secondary" @click="counterReset">重置</button>
          </div>
          <div class="code-snippet">
            <CodeBlock code="function useCounter(initialValue = 0) {
  const count = ref(initialValue);
  const increment = () => count.value++;
  const decrement = () => count.value--;
  const reset = () => count.value = initialValue;
  
  return { count, increment, decrement, reset };
}" language="javascript"></CodeBlock>
          </div>
        </div>
      </div>
      
      <!-- 计时器组合式函数 -->
      <div class="demo-card">
        <h3 class="card-title">useTimer - 计时器</h3>
        <div class="demo-content">
          <div class="timer-display">
            秒数: <span class="seconds-value">{{ timerSeconds }}</span>
          </div>
          <div class="button-group">
            <button class="action-btn" @click="timerStart">开始</button>
            <button class="action-btn" @click="timerStop">停止</button>
            <button class="action-btn secondary" @click="timerReset">重置</button>
          </div>
        </div>
      </div>
      
      <!-- 本地存储组合式函数 -->
      <div class="demo-card">
        <h3 class="card-title">useLocalStorage - 本地存储</h3>
        <div class="demo-content">
          <div class="storage-input-group">
            <input 
              v-model="savedText" 
              type="text" 
              class="storage-input"
              placeholder="输入要保存的内容"
            />
            <button class="action-btn" @click="saveText(savedText)">保存</button>
            <button class="action-btn secondary" @click="removeText">清除</button>
          </div>
          <p class="storage-status">
            数据已保存在localStorage中，刷新页面后仍然存在
          </p>
        </div>
      </div>
      
      <!-- 表单验证组合式函数 -->
      <div class="demo-card">
        <h3 class="card-title">useFormValidator - 表单验证</h3>
        <div class="demo-content">
          <form @submit.prevent class="validator-form">
            <div class="form-group">
              <label>用户名:</label>
              <input 
                type="text" 
                :value="formValidator.data.username" 
                @input="formValidator.updateField('username', $event.target.value)"
                :class="['form-input', { 'error': formValidator.errors.username }]"
              />
              <span v-if="formValidator.errors.username" class="error-message">
                {{ formValidator.errors.username }}
              </span>
            </div>
            <div class="form-group">
              <label>邮箱:</label>
              <input 
                type="email" 
                :value="formValidator.data.email" 
                @input="formValidator.updateField('email', $event.target.value)"
                :class="['form-input', { 'error': formValidator.errors.email }]"
              />
              <span v-if="formValidator.errors.email" class="error-message">
                {{ formValidator.errors.email }}
              </span>
            </div>
          </form>
        </div>
      </div>
      
      <!-- 鼠标位置组合式函数 -->
      <div class="demo-card">
        <h3 class="card-title">useMouse - 鼠标位置</h3>
        <div class="demo-content">
          <div class="mouse-position">
            <p>鼠标 X 坐标: {{ mouseX }}</p>
            <p>鼠标 Y 坐标: {{ mouseY }}</p>
          </div>
          <div class="button-group">
            <button class="action-btn" @click="startMouseTracking">开始跟踪</button>
            <button class="action-btn secondary" @click="stopMouseTracking">停止跟踪</button>
          </div>
        </div>
      </div>
      
      <!-- 网络请求组合式函数 -->
      <div class="demo-card">
        <h3 class="card-title">useFetch - 网络请求</h3>
        <div class="demo-content">
          <button class="action-btn" @click="fetchApiData">获取数据</button>
          <div v-if="apiLoading" class="loading-state">加载中...</div>
          <div v-else-if="apiError" class="error-state">错误: {{ apiError }}</div>
          <div v-else-if="apiData" class="api-data">
            <CodeBlock :code="JSON.stringify(apiData, null, 2)" language="json"></CodeBlock>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 组合式函数最佳实践 -->
    <div class="best-practices-section">
      <h3 class="section-title">组合式函数最佳实践</h3>
      <ul class="best-practices-list">
        <li><strong>命名规范:</strong> 使用 use 开头的驼峰命名法 (如 useCounter)</li>
        <li><strong>状态隔离:</strong> 每个组合式函数应创建独立的响应式状态</li>
        <li><strong>资源清理:</strong> 提供清理函数或在内部管理资源生命周期</li>
        <li><strong>逻辑复用:</strong> 提取通用逻辑，避免重复代码</li>
        <li><strong>组合嵌套:</strong> 可以在一个组合式函数中使用另一个组合式函数</li>
        <li><strong>返回值:</strong> 通常返回一个包含响应式数据和方法的对象</li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.composables-demo {
  padding: 20px;
}

.demo-title {
  text-align: center;
  margin-bottom: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.demo-description {
  text-align: center;
  margin-bottom: 30px;
  color: #666;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.demo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.demo-card {
  background: white; /* 浅色主题下为白色背景 */
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: all 0.2s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 深色主题下的样式 */
[data-theme="dark"] .demo-card {
  background: #000000; /* 深色主题下为黑色背景 */
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  color: #ffffff;
}

.card-title {
  color: #667eea;
  margin-bottom: 15px;
}

.demo-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 按钮样式 */
.button-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background-color: #667eea;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-btn:hover {
  background-color: #764ba2;
}

.action-btn.secondary {
  background-color: #f5f5f5;
  color: #333;
}

.action-btn.secondary:hover {
  background-color: #e0e0e0;
}

/* 计数器样式 */
.counter-display, .timer-display {
  text-align: center;
  font-size: 1.2rem;
  margin-bottom: 10px;
}

.count-value, .seconds-value {
  font-size: 2rem;
  font-weight: bold;
  color: #667eea;
}

/* 本地存储样式 */
.storage-input-group {
  display: flex;
  gap: 10px;
}

.storage-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.storage-status {
  color: #666;
  font-size: 0.9rem;
  margin-top: 10px;
}

/* 表单验证样式 */
.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.form-input.error {
  border-color: #ff6b6b;
}

.error-message {
  display: block;
  color: #ff6b6b;
  font-size: 0.8rem;
  margin-top: 5px;
}

/* 鼠标位置样式 */
.mouse-position {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 6px;
}

.mouse-position p {
  margin: 5px 0;
}

/* API请求样式 */
.loading-state {
  text-align: center;
  color: #666;
  padding: 20px;
}

.error-state {
  color: #ff6b6b;
  padding: 10px;
  background-color: #ffe6e6;
  border-radius: 6px;
}

.api-data {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 6px;
  overflow-x: auto;
}

.api-data pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.9rem;
}

/* 代码片段样式 */
.code-snippet {
  background-color: #f5f5f5;
  border-radius: 5px;
  padding: 10px;
  overflow-x: auto;
}

.code-snippet pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.8rem;
  color: #333;
}

/* 最佳实践部分 */
.best-practices-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-top: 30px;
}

.section-title {
  color: #667eea;
  margin-bottom: 15px;
}

.best-practices-list {
  padding-left: 20px;
}

.best-practices-list li {
  margin-bottom: 8px;
  color: #555;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .demo-grid {
    grid-template-columns: 1fr;
  }
  
  .storage-input-group {
    flex-direction: column;
  }
}
</style>